import React, { useCallback, useEffect, useMemo, useState, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useVoiceRecognition } from '../../hooks/useVoiceRecognition';
import { useAuth } from '../../hooks/useAuth';
import { VoiceRecognitionResult } from '../../types/speechRecognition';
// import VoiceDiagnostics from './VoiceDiagnostics';

interface VoiceInputButtonProps {
  onResult: (text: string) => void;
  onError?: (error: string) => void;
  disabled?: boolean;
  className?: string;
  showDiagnostics?: boolean; // 是否显示诊断工具
  size?: 'small' | 'large'; // 尺寸模式：small为原始小按钮，large为和输入框一样大
  variant?: 'button' | 'input'; // 变体：button为按钮样式，input为输入框样式
}

/**
 * 语音输入按钮组件
 * 
 * 功能：
 * - 点击开始/停止语音识别
 * - 实时显示识别状态
 * - 将识别结果回传给父组件
 * - 登录状态检查
 * - 支持小按钮和大输入框两种尺寸
 * - 支持向上滑动取消录音
 */
const VoiceInputButton: React.FC<VoiceInputButtonProps> = React.memo(({
  onResult,
  onError,
  disabled = false,
  className = '',
  size = 'small',
  variant = 'button'
//   showDiagnostics = false
}) => {
//   const [showDiagnosticsModal, setShowDiagnosticsModal] = useState(false);
  const { t } = useTranslation();
  const { isLoggedIn, checkLoginAndShowModal } = useAuth();

  // 滑动相关状态
  const [startY, setStartY] = useState<number>(0);
  const [isCancelMode, setIsCancelMode] = useState<boolean>(false);
  const buttonRef = useRef<HTMLButtonElement>(null);

  // 语音识别Hook
  const {
    status,
    isListening,
    currentText,
    error,
    startListening,
    stopListening,
    resetText
  } = useVoiceRecognition({
    userId: 1, // 固定userId
    engineType: '16k_zh',
    onResult: useCallback((result: VoiceRecognitionResult) => {
      // console.log('🎤 语音识别实时结果:', result);
      // 注意：这里不再自动调用onResult，只用于实时显示
      // 最终结果处理将在用户松开按钮时进行
    }, []),
    onError: useCallback((errorMsg: string) => {
      // console.error('🎤 语音识别错误:', errorMsg);
      console.error('voice recognition error',errorMsg);
      onError?.(errorMsg);
    }, [onError])
  });

  // 重置滑动状态
  const resetSwipeState = useCallback(() => {
    setStartY(0);
    setIsCancelMode(false);
  }, []);

  // 处理按下开始录音
  const handleMouseDown = useCallback(async (e: React.MouseEvent | React.TouchEvent) => {
    e.preventDefault();
    
    // 检查登录状态
    if (!isLoggedIn) {
      if (checkLoginAndShowModal()) {
        return; // 如果需要登录，直接返回
      }
    }

    if (disabled || isListening) return;

    // 记录开始位置
    const clientY = 'touches' in e ? e.touches[0].clientY : e.clientY;
    setStartY(clientY);
    setIsCancelMode(false);

    try {
      // console.log('🎤 开始录音 - 按下按钮');
      // 开始识别
      resetText(); // 清除之前的文本，开始新的识别
      await startListening();
    } catch (err) {
      // console.error('🎤 开始录音失败:', err);
      console.error('start recording failed',err);
      onError?.(err instanceof Error ? err.message : 'start recording failed');

      resetSwipeState();
    }
  }, [
    isLoggedIn, 
    checkLoginAndShowModal, 
    disabled, 
    isListening,
    resetText, 
    startListening, 
    onError,
    resetSwipeState
  ]);

  // 处理滑动移动
  const handleMove = useCallback((e: React.MouseEvent | React.TouchEvent) => {
    if (!isListening) return;

    const clientY = 'touches' in e ? e.touches[0].clientY : e.clientY;

    // 计算向上滑动距离
    const deltaY = startY - clientY;
    
    // 如果向上滑动超过30px，进入取消模式
    if (deltaY > 80) {
      setIsCancelMode(true);
    } else {
      setIsCancelMode(false);
    }
  }, [isListening, startY]);

  // 处理松开停止录音
  const handleMouseUp = useCallback(async () => {
    if (disabled || !isListening) return;

    try {
      // 停止识别
      stopListening();
      
      if (isCancelMode) {
        // 取消模式：不发送消息
        // console.log('🎤 取消录音 - 用户向上滑动');
      } else {
        // 正常模式：发送消息
        // console.log('🎤 停止录音 - 用户松开按钮，准备发送消息');
        
        // 获取当前识别的文本（在停止前）
        const finalText = currentText.trim();
        
        // 立即处理最终结果，不依赖异步回调
        // console.log('🎤 最终录音转换结果:', finalText);
        
        if (finalText) {
          // console.log('🎤 发送识别结果给父组件:', finalText);
          onResult(finalText);
        } else {
          // console.log('🎤 未识别到有效文本，不发送');
        }
      }
    } catch (err) {
      // console.error('🎤 停止录音失败:', err);
      console.error('stop recording failed',err);
      onError?.(err instanceof Error ? err.message : 'stop recording failed');
    } finally {
      resetSwipeState();
    }
  }, [disabled, isListening, stopListening, currentText, onResult, onError, isCancelMode, resetSwipeState]);

  // 处理鼠标离开（防止用户拖拽离开按钮）
  const handleMouseLeave = useCallback(() => {
    if (isListening) {
      // console.log('🎤 用户拖拽离开按钮 - 自动停止录音');
      handleMouseUp();
    }
  }, [isListening, handleMouseUp]);

  // 阻止上下文菜单（长按菜单）
  const handleContextMenu = useCallback((e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    return false;
  }, []);

  // 阻止拖拽开始
  const handleDragStart = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    return false;
  }, []);

  // 错误状态处理
  useEffect(() => {
    if (error) {
      onError?.(error);
    }
  }, [error, onError]);

  // 获取按钮样式 - 使用useMemo优化
  const buttonStyle = useMemo(() => {
    const baseStyle = size === 'large' && variant === 'input' 
      ? 'w-full px-4 py-3 rounded-2xl min-h-[48px] max-h-[120px]' 
      : 'flex-shrink-0 w-10 h-10 rounded-full';
    
    if (disabled) {
      return `${baseStyle} bg-gray-600 text-gray-400 cursor-not-allowed`;
    }

    let colorStyle = '';
    if (isCancelMode) {
      // 取消模式的样式
      colorStyle = 'bg-red-600 text-white';
    } else {
      switch (status) {
        case 'listening':
          colorStyle = 'bg-red-500 text-white animate-pulse hover:bg-red-600';
          break;
        case 'initializing':
          colorStyle = 'bg-yellow-500 text-white animate-pulse';
          break;
        case 'processing':
          colorStyle = 'bg-blue-500 text-white animate-pulse';
          break;
        case 'error':
          colorStyle = 'bg-red-600 text-white';
          break;
        default:
          colorStyle = variant === 'input' 
            ? 'bg-gray-700 text-white hover:bg-gray-600' 
            : 'bg-pink-500 text-white hover:bg-pink-600';
          break;
      }
    }

    return `${baseStyle} ${colorStyle}`;
  }, [disabled, status, size, variant, isCancelMode]);

  // 获取图标类型 - 使用useMemo优化
  const iconClass = useMemo(() => {
    if (isCancelMode) {
      return 'fas fa-times';
    }
    
    switch (status) {
      case 'listening':
        return 'fas fa-stop';
      case 'initializing':
      case 'processing':
        return 'fas fa-spinner fa-spin';
      case 'error':
        return 'fas fa-exclamation-triangle';
      default:
        return 'fas fa-microphone';
    }
  }, [status, isCancelMode]);

  // 获取提示文本 - 使用useMemo优化
  const tooltipText = useMemo(() => {
    if (!isLoggedIn) {
      return t('chat.loginRequired');
    }

    if (isCancelMode) {
      return t('chat.releaseToCancel');
    }

    switch (status) {
      case 'listening':
        return t('chat.recording');
      case 'initializing':
        return t('chat.initializing');
      case 'processing':
        return t('chat.connecting');
      case 'error':
        return `${t('chat.voiceRecognitionError')}: ${error}`;
      default:
        return t('chat.holdToRecord');
    }
  }, [isLoggedIn, status, error, isCancelMode, t]);

  // 获取按钮的显示文本（仅在大尺寸输入框样式时显示） - 使用useMemo优化
  const displayText = useMemo(() => {
    if (size !== 'large' || variant !== 'input') return null;
    
    // 不再在按钮内显示识别文本，只显示状态文本
    if (isCancelMode) {
      return t('chat.releaseToCancel');
    }
    
    switch (status) {
      case 'listening':
        return t('chat.swipeUpToCancel');
      case 'initializing':
        return t('chat.initializingShort');
      case 'processing':
        return t('chat.connectingShort');
      case 'error':
        return `${t('chat.error')}: ${error}`;
      default:
        return t('chat.holdToRecord');
    }
  }, [size, variant, status, error, isCancelMode, t]);

      return (
      <div className="relative group">
        {/* 识别文本气泡框 - 在按钮上方显示 */}
        {currentText && isListening && !isCancelMode && (
          <div className="absolute bottom-full left-1/2 transform -translate-x-1/2 mb-3 
                          bg-white text-gray-800 px-4 py-2 rounded-lg shadow-lg z-20
                          max-w-[280px] min-w-[120px] border border-gray-200">
            {/* 气泡小箭头 */}
            <div className="absolute top-full left-1/2 transform -translate-x-1/2 
                            w-0 h-0 border-l-6 border-r-6 border-t-6 
                            border-l-transparent border-r-transparent border-t-white">
            </div>
            {/* 文本内容 */}
            <div className="text-sm leading-relaxed break-words">
              {currentText}
            </div>
          </div>
        )}

        <button
          ref={buttonRef}
          onMouseDown={handleMouseDown}
          onMouseMove={handleMove}
          onMouseUp={handleMouseUp}
          onMouseLeave={handleMouseLeave}
          onTouchStart={handleMouseDown}
          onTouchMove={handleMove}
          onTouchEnd={handleMouseUp}
          onContextMenu={handleContextMenu}
          onDragStart={handleDragStart}
          disabled={disabled}
          className={`
            flex items-center justify-center 
            transition-all duration-200 transform active:scale-95
            select-none touch-manipulation
            ${buttonStyle}
            ${className}
          `}
          style={{
            userSelect: 'none',
            WebkitUserSelect: 'none',
            WebkitTouchCallout: 'none',
            WebkitTapHighlightColor: 'transparent'
          }}
          title={tooltipText}
        >
        {size === 'large' && variant === 'input' ? (
          // 大尺寸输入框样式：只显示居中文本（不包含识别文本）
          <span className="text-white text-center w-full truncate">
            {displayText}
          </span>
        ) : (
          // 小按钮样式：只显示图标
          <i className={`${iconClass} text-sm`} />
        )}
      </button>

      {/* 语音识别状态指示器 */}
      {isListening && !isCancelMode && (
        <div className="absolute -top-1 -right-1 w-3 h-3 bg-red-500 rounded-full animate-pulse">
          <div className="absolute inset-0 bg-red-500 rounded-full animate-ping opacity-75"></div>
        </div>
      )}

      {/* 取消模式UI提示 */}
      {isCancelMode && (
        <div className="absolute -top-12 left-1/2 transform -translate-x-1/2 
                        bg-red-600 text-white px-3 py-1 rounded-lg shadow-lg z-20
                        flex items-center space-x-2">
          <i className="fas fa-arrow-up text-sm"></i>
          <i className="fas fa-times text-sm"></i>
        </div>
      )}

      {/* 错误提示 */}
      {error && status === 'error' && (
        <div className="absolute top-12 left-1/2 transform -translate-x-1/2 
                        bg-red-600 text-white text-xs px-2 py-1 rounded 
                        max-w-[200px] z-10">
          {error}
        </div>
      )}
    </div>
  );
});

VoiceInputButton.displayName = 'VoiceInputButton';

export default VoiceInputButton; 